const path = require('path')
const Koa = require('koa')
const app = new Koa()
const router = require('./router')
const static = require('koa-static')
const db = require('./db')

app.use(static(path.resolve(__dirname, '../client')))

app.use(async (ctx, next) => {
    ctx.data = ctx.request.data = {}
    if(ctx.method === 'POST'){
        let data = await new Promise(resolve => {
            let str = ''
            ctx.req.on('data', chunk => {
                str += chunk
            })
            ctx.req.on('end', () => {
                resolve(str)
            })
        })
        try{
            if(data) ctx.data = ctx.request.data = JSON.parse(data)
        }catch(err){
            return ctx.body = JSON.stringify({
                code: 2,
                msg: '参数错误，只接收Application/json'
            })
        }
    }
    await next();
})

app.use(async (ctx, next) => {
    ctx.success = data => {
        ctx.type = 'application/json'
        ctx.body = {
            code: 0,
            msg: '成功',
            data
        }
    }
    ctx.fail = (msg, code) => {
        ctx.type = 'application/json'
        ctx.body = {
            code: code || 3,
            msg
        }
    }
    await next()
})

app.use(db)

app.use(router.routes()).use(router.allowedMethods())

app.use(async ctx => {
    if(ctx.method === 'GET'){
        ctx.status = 404
        ctx.type = 'text/html'
        ctx.body = '<h1>404：木有找到，英文叫：Not found</h1>'
    }else{
        ctx.type = 'appliction/json'
        ctx.body = {
            code: 404,
            msg: '木有这个接口'
        }
    }
})

app.listen(1009);
